# !/usr/bin/python
# -*- coding: UTF-8 -*-
"""
@author:zzly
@file:serializers.py
@time:2020/09/08
"""
from rest_framework import serializers
from apps.adorn_pedia.models import AdornPedia, AdornPediaImgs
from apps.member.product.serializers import ProductAppSeializer
from apps.system.serializers import UploadSerializer
from apps.system.models import Option


class AdornPediaCategorySerializer(serializers.ModelSerializer):
    adorn_pedia = serializers.SerializerMethodField()

    def get_adorn_pedia(self, obj):
        adorn_pedias = AdornPedia.objects.filter(category=obj)
        ser = AdornPediaAppSeializer(instance=adorn_pedias, many=True)
        return ser.data

    class Meta:
        model = Option
        fields = ('id', 'name', 'adorn_pedia')


class AdornPediaAppSeializer(serializers.ModelSerializer):
    # thumbnail = serializers.SerializerMethodField(read_only=True)
    # category_text = serializers.CharField(source='category.name')

    #
    # def get_thumbnail(self, obj):
    #     if obj.thumbnail:
    #         return obj.thumbnail.get_url()
    #     return ''

    class Meta:
        model = AdornPedia
        fields = ('id', 'name', 'icon', 'color')


class AdornPediaDetailAppSeializer(serializers.ModelSerializer):
    thumbnail = serializers.SerializerMethodField(read_only=True)
    abstract = serializers.SerializerMethodField()
    relate_products = serializers.SerializerMethodField()

    def get_relate_products(self, obj):
        return ProductAppSeializer(obj.relate_products, many=True).data

    def get_abstract(self, obj):
        if obj.abstract:
            return obj.abstract.split('|')
        return []

    def get_thumbnail(self, obj):
        if obj.thumbnail:
            return obj.thumbnail.get_url()
        return ''

    class Meta:
        model = AdornPedia
        fields = ('thumbnail', 'id', 'name', 'abstract', 'content', 'relate_products')


class AdornPediaImgsSerializers(serializers.ModelSerializer):
    image = serializers.SerializerMethodField()

    def get_image(self, obj):
        if obj.image:
            return obj.image.get_url()
        return ''

    class Meta:
        model = AdornPediaImgs
        fields = ('image',)
